import {View, Text, Alert, ActivityIndicator, FlatList, NativeModules, Platform, SafeAreaView, StatusBar} from 'react-native';
import React, {PureComponent} from 'react';
import {Flex, Modal, WhiteSpace, WingBlank} from '@ant-design/react-native';
import {connect} from 'react-redux';
import {getProjectListByOwner} from '~/api/home';
import HCard from '~/components/h-card';
import SearchView from '~/components/home/search';
import BannerView from '~/components/home/banner';
import NoticeView from '~/components/home/notice';
import MapView from '~/components/home/map';
import TabView from '~/components/home/tab';

import Homeleaseale from '~/components/zs-card/Homeleaseale';
import {saveSystem} from '~/store/system';
import {getGeoCity} from '~/api/public';
import {getParkingRentList} from '~/api/parking';
import {getHttpUrl} from '~/api/basic';

let statusBarHeight;
if (Platform.OS === 'ios') {
    const {StatusBarManager} = NativeModules;
    StatusBarManager.getHeight((window) => {
        statusBarHeight = window.height;
    });
} else {
    statusBarHeight = StatusBar.currentHeight;
}

const mapGetter = (state) => {
    return {
        userinfo: state.userinfo,
        system: state.system,
    };
};

const mapSetter = (dispatch) => {
    return {
        onSave: (data) => {
            dispatch(saveSystem(data));
        },
    };
};

class Home extends PureComponent {
    static navigationOptions = {
        headerShown: false,
    };

    constructor(props) {
        super(props);
        this.state = {
            CityName: '', // 城市名称
            CityID: 0, //城市id
            bannerList: [], //广告列表
            noticeList: [], //公告列表
            dataList: [],
            page_index: 1, //页
            page_size: 10, //每页条数
            is_next: true,
            loading: true,
            refreshing: false,
            list_type: 1, //1活动,2租车位,3售车位
            baseurl: '',
        };
        getHttpUrl().then((r) => {
            if (r.code === 0) {
                this.setState({
                    baseurl: r.data,
                });
            }
        });
    }

    componentDidMount() {
        //设定城市
        this.setCityInfo();
    }

    //设置所在城市
    setCityInfo = () => {
        if (this.props.system.city_id === 0) {
            getGeoCity({city_id: this.props.system.adcode}).then((r) => {
                if (r.code === 0) {
                    let city = r.data.CityName;
                    let city_id = r.data.PuCityID;
                    this.state.CityName = city;
                    this.state.CityID = city_id;
                    this.props.onSave({
                        city,
                        city_id,
                    });
                    this.reloadData();
                } else {
                    if (r.msg !== 'Network Error') {
                        Modal.alert('提示', '你所在城市未开放，请手动选择其它开放的城市。', [
                            {
                                text: '确定',
                                onPress: () => {
                                    this.onGoCityPage();
                                },
                            },
                        ]);
                    }
                }
            });
        } else {
            this.state.CityName = this.props.system.city;
            this.state.CityID = this.props.system.city_id;
            this.reloadData();
        }
    };

    //跳转选择城市页面
    onGoCityPage = () => {
        this.props.navigation.push('City', {
            updateCityName: (CityName, CityID) => {
                this.state.CityName = CityName;
                this.state.CityID = CityID;
                this.reloadData();
            },
        });
    };

    //跳转搜索页面
    onGoSearchPage = () => {
        this.props.navigation.push('SearchHome', {
            listtype: this.state.list_type,
            CityID: this.state.CityID,
            CityName: this.state.CityName,
        });
    };

    //跳转地图页面
    onGoMapPage = () => {
        this.props.navigation.push('Map');
    };

    //租售车位列表
    getRentList() {
        getParkingRentList({
            page_index: this.state.page_index++,
            page_size: this.state.page_size,
            condidate: {
                puCityID: this.state.CityID,
                rentType: this.state.list_type - 2, //0出租  1出售
            },
        }).then((r) => {
            if (r.code === 0) {
                if (r.data.list.length === 0) {
                    this.setState({is_next: false});
                } else {
                    let list = this.state.dataList.concat(r.data.list);
                    this.setState({dataList: list});
                }
            } else {
                Alert.alert('错误', r.msg);
            }
        });
    }

    //获取活动列表
    getProjectList = () => {
        getProjectListByOwner({
            cityId: this.state.CityID,
            buildingName: '',
            page_index: this.state.page_index++,
            page_size: this.state.page_size,
        }).then((r) => {
            if (r.code === 0) {
                if (r.data.page_data.list.length === 0) {
                    this.setState({is_next: false});
                } else {
                    let list = this.state.dataList.concat(r.data.page_data.list);
                    this.setState({dataList: list});
                }
            } else {
                Alert.alert('错误', r.msg);
            }
        });
    };

    switchType = (type) => {
        this.state.list_type = type;
        this.reloadData();
    };

    //下拉刷新
    reloadData = () => {
        this.state.page_index = 1;
        this.state.dataList = [];
        this.setState({is_next: true, loading: true});
        if (this.state.list_type === 1) {
            this.getProjectList();
        } else {
            this.getRentList();
        }
    };

    //上拉加载更多
    loadData = () => {
        if (this.state.is_next) {
            this.setState({refreshing: false, loading: true});
            if (this.state.list_type === 1) {
                this.getProjectList();
            } else {
                this.getRentList();
            }
        }
    };

    _renderItem({item}) {
        return (
            <View style={{width: '47.5%', marginRight: '5%', marginBottom: 15}}>
                <Flex
                    style={{
                        width: '100%',
                    }}
                    onPress={() => {
                        this.state.list_type === 1
                            ? this.props.navigation.push('CommunityInfo', {
                                  params: item.ProjectDataID,
                              })
                            : this.props.userinfo.token === ''
                            ? this.props.navigation.push('Login')
                            : this.props.navigation.push('ParkRentInfo', {params: item.ParkingRentID});
                    }}>
                    {this.state.list_type === 1 ? <HCard item={item} baseurl={this.state.baseurl} /> : <Homeleaseale item={item} />}
                </Flex>
            </View>
        );
    }

    _HeaderView = () => {
        return (
            <View>
                {/* 搜索栏 */}
                <SearchView CityName={this.state.CityName} onGoCityPage={this.onGoCityPage} onGoSearchPage={this.onGoSearchPage} />
                <WhiteSpace />
                {/* 轮播图 */}
                <BannerView />
                <WhiteSpace />
                {/* 公告栏 */}
                <NoticeView navigation={this.props.navigation} />
                {/* 地图入口 */}
                <MapView onPress={this.onGoMapPage} />
                <WhiteSpace />
                {/* 标签页 */}
                <TabView onPress={this.switchType} onMore={this.onGoSearchPage} />
                <WhiteSpace />
            </View>
        );
    };

    //上拉底部显示
    _FooterView = () => {
        if (this.state.is_next) {
            if (this.state.loading) {
                return <ActivityIndicator size="small" color="#999999" style={{marginBottom: 15}} />;
            }
        } else {
            return (
                <View style={{height: 35, alignItems: 'center'}}>
                    <Text style={{color: '#999999', fontSize: 14}}>~ 已经到底了 ~</Text>
                </View>
            );
        }
    };

    render() {
        return (
            <SafeAreaView style={{marginTop: statusBarHeight}}>
                <WingBlank>
                    <FlatList
                        data={this.state.dataList}
                        numColumns={2}
                        showsVerticalScrollIndicator={false}
                        renderItem={(data) => this._renderItem(data)}
                        keyExtractor={(item, index) => index}
                        ListHeaderComponent={this._HeaderView}
                        ListFooterComponent={this._FooterView}
                        onEndReached={() => this.loadData()}
                        onEndReachedThreshold={0.1}
                        onRefresh={this.reloadData}
                        refreshing={this.state.refreshing}
                    />
                </WingBlank>
            </SafeAreaView>
        );
    }
}

export default connect(mapGetter, mapSetter)(Home);
